package t1;

import java.io.FileInputStream;

/**
 * Simple class loader to illustrate custom Class loading with new delegation
 * model in Java 1.2.
 */
public class SimpleClassLoader2 extends ClassLoader {
	/**
	 * Provide delegation constructor
	 */
	SimpleClassLoader2(ClassLoader parent) {
		super(parent);
	}

	/**
	 * Same old ClassLoader constructor
	 */
	SimpleClassLoader2() {
		super();
	}

	/**
	 * This is the method where the task of class loading is delegated to
	 * ourcustom loader.
	 * 
	 */
	protected Class findClass(String name) throws ClassNotFoundException {
		FileInputStream fi = null;
		try {
			System.out.println("SimpleClassLoader2 finding class: " + name);
//			String path = name.replace('.', '/');
			fi = new FileInputStream(name + ".class");
			byte[] classBytes = new byte[fi.available()];
			fi.read(classBytes);
			return defineClass(name, classBytes, 0, classBytes.length);
		} catch (Exception e) {
			// We could not find the class, so indicate the problem with an
			// exception
			throw new ClassNotFoundException(name);
		} finally {
			if (null != fi) {
				try {
					fi.close();
				} catch (Exception e) {
				}
			}
		}
	}

	public static void main(String args[]) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException {
		SimpleClassLoader2 loader = new SimpleClassLoader2();
		Runnable r = (Runnable) loader.loadClass("Echo").newInstance();
		r.run();
	}
}